package Redis

import (
	"baikBingo/pkg/Util"
	"fmt"
	"time"

	"github.com/go-redis/redis"
)

var (
	addr     = Util.Config("env.redis.host") + ":" + Util.Config("env.redis.port")
	password = Util.Config("env.redis.password")
	prefix   = Util.Config("env.redis.prefix")
)

//连接redis
func connect() *redis.Client {
	client := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: password,
		DB:       0,
	})
	_, err := client.Ping().Result()
	if err != nil {
		fmt.Printf("err_handler, error:%s\n", err.Error())
		panic(err.Error())
	}
	return client
}

//检查给定 key 是否存在。
func Exists(key string) bool {
	client := connect()
	defer client.Close()
	result, _ := client.Exists(prefix + key).Result()
	if result == 1 {
		return true
	}
	return false
}

//设置指定 key 的值及过期时间， 0为永久
func Set(key string, value string, expire int) {
	client := connect()
	defer client.Close()
	client.Set(prefix+key, value, time.Duration(expire)*time.Second)
}

//获取指定 key 的值
func Get(key string) string {
	client := connect()
	defer client.Close()
	val, err := client.Get(prefix + key).Result()
	if err != nil {
		return ""
	}
	return val
}

//在 key 存在时删除 key
func Del(key string) {
	client := connect()
	defer client.Close()
	client.Del(prefix + key)
}

// 向key的hash中添加元素field的值
func HSet(key, field string, data string) {
	client := connect()
	defer client.Close()
	client.HSet(prefix+key, field, data)
}

// 批量向key的hash添加对应元素field的值
func HMSet(key string, fields map[string]interface{}) {
	client := connect()
	defer client.Close()
	client.HMSet(prefix+key, fields)
}

// 通过key获取hash的元素值
func HGet(key, field string) string {
	client := connect()
	defer client.Close()
	val, err := client.HGet(prefix+key, field).Result()
	if err == redis.Nil {
		return ""
	} else if err != nil {
		return ""
	}
	return val
}

// 批量获取key的hash中对应多元素值
func HMGet(key string, fields ...string) map[string]interface{} {
	client := connect()
	defer client.Close()
	resMap := make(map[string]interface{})
	for _, field := range fields {
		var result interface{}
		val, err := client.HGet(prefix+key, fmt.Sprintf("%s", field)).Result()
		if err == redis.Nil {
			resMap[field] = result
		} else if err != nil {
			resMap[field] = result
		}
		if val != "" {
			resMap[field] = val
		} else {
			resMap[field] = result
		}
	}
	return resMap
}
